package cn.gqr.controller.fore;

import cn.gqr.entity.Cart;
import cn.gqr.entity.Order;
import cn.gqr.entity.OrderItem;
import cn.gqr.entity.User;
import cn.gqr.service.CartService;
import cn.gqr.service.OrderService;
import cn.gqr.tool.GetUser;
import cn.gqr.tool.RespJson;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Map;

//登录后 购物车
@RestController
@RequestMapping("/api/fore/cart")
public class CartController {

    @Autowired
    CartService cartService;
    @Autowired
    OrderService orderService;

    //查询该用户全部购物车
    @RequestMapping("/findAll")
    public Map<String, Object> findAll(){
        User user = (User)GetUser.getUser();
        System.out.println(user.getId());
        if(user.getId()==0){
            return RespJson.pack(401,"未登录",null);
        }
        return RespJson.pack(200,"",cartService.findAll(user.getId()));
    }

    //购物车转订单
    @PostMapping("/addCart2Order")
    public Map<String, Object> addCart2Order(@RequestBody List<OrderItem> lst){
        System.out.println(lst);
        //总价
        double amount = 0;
        for (OrderItem orditem : lst) {
            //计算总价
            amount += orditem.getNum()*orditem.getPrice();
        }
        //token获取用户
        User user = (User)GetUser.getUser();

        //等于0 未登录或登录超时
        if(user.getId()==0){
            return RespJson.pack(401, "未登录或登录超时", null);
        }

        Order order = new Order();
        order.setUid(user.getId());
        order.setAmount(amount);
        return cartService.addCart2Order(order,lst);
    }

    //添加购物车
    @RequestMapping("/addCart")
    public Map<String, Object> addCart(Cart cart){
        return cartService.addCart(cart);
    }

    //删除购物车
    @GetMapping("/delCart/{id}")
    public Map<String, Object> delCart(@PathVariable("id")int id){
        User user = (User)GetUser.getUser();
        int i = cartService.delCart(id);
        return RespJson.pack(200,i>0?"删除成功":"删除失败",cartService.findAll(user.getId()));
    }

}
